<?php
namespace app\api\controller\xilumarket;

use addons\xilumarket\controller\WeixinMini;
use app\common\controller\XilumarketApi;
use app\common\model\xilumarket\FooterView;
use app\common\model\xilumarket\Product AS ProductModel;
use app\common\model\xilumarket\UserCollection;
use app\common\model\xilumarket\UserFocus;
use PHPQRCode\QRcode;
use think\Exception;
use function fast\array_get;

class Product extends XilumarketApi
{
    protected $noNeedLogin = ['lists','hot_lists','lists','detail'];
    protected $noNeedRight = ['*'];

    /**
     * 新增闲置
     */
    public function add(){
        $params = $this->request->param('');
        try {
            $ret = ProductModel::add($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('查询成功',$ret);
    }

    /**
     * 上下架
     */
    public function multi_status(){
        $params = $this->request->param('');
        try {
            $ret = ProductModel::multiStatus($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('查询成功',$ret);
    }

    /**
     * 闲置列表
     */
    public function lists(){
        $params = $this->request->param('');
        $params['city_id'] = $this->cityid;
        $result = ProductModel::lists($params,$this->auth->id);
        $this->success('查询成功', array_merge($result->toArray(), ['extrend' => [\app\common\model\xilumarket\Topic::where([])->find()]]));
    }

    /**
     * 闲置详情
     */
    public function detail(){
        $params = $this->request->param('');
        $product_id = array_get($params,'product_id');
        $product = $product_id?ProductModel::detail ($product_id):null;
        if(!$product){
            $this->error('商品不存');
        }
        $product->is_collection_count = $this->auth->isLogin() ? UserCollection::isFav($this->auth->id,$product_id,UserCollection::TYPE_PRODUCT) : 0;
        $product->is_focus_count = $this->auth->isLogin() ? UserFocus::isFocus($this->auth->id,$product->user_id) : 0;

        #足迹
        if($this->auth->isLogin()){
            try {
                FooterView::viewFooter($this->auth->id,$product_id,FooterView::TYPE_PRODUCT);
            }catch (Exception $e){
                //$this->error($e->getMessage());
            }
        }
        $this->success('查询成功', $product);
    }

    /**
     * 我发布的闲置列表
     */
    public function mylists(){
        $params = $this->request->param('');
        $result = ProductModel::mylists($params,$this->auth->id);
        $this->success('查询成功', $result);
    }

    /**
     * 我的商品删除
     */
    public function del(){
        $params = $this->request->param('');
        try {
            $result = ProductModel::del($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('删除成功');
    }
    /**
     * @ApiTitile (修改价格)
     * @ApiSummary (修改价格)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilumarket.product/toggle_collection)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=product_id, type=int, require=true, description="id")
     */
    public function change_price(){
        $params = $this->request->post('');
        if(!$params){
            $this->error("参数错误");
        }
        try {
            $ret = ProductModel::changePrice($params,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('修改成功',$ret);
    }

    /**
     * @ApiTitile (复制商品)
     * @ApiSummary (复制商品)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilumarket.product/copy_product)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=product_id, type=int, require=true, description="id")
     */
    public function copy_product(){
        $product_id = $this->request->post('product_id');
        $product = $product_id?ProductModel::field("product_type,category_id,name,province_id,city_id,region_id,street,address,lat,lng,thumb_image,salesprice,line_price,freight_status,freight_money,images,content")->where('id',$product_id)->find():null;
        if(!$product){
            $this->error("未找到产品");
        }
        try {
            $ret = ProductModel::add($product->toArray(),$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('查询成功',$ret);
    }

    /**
     * @ApiTitile (收藏&取消收藏)
     * @ApiSummary (收藏&取消收藏)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilumarket.product/toggle_collection)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=product_id, type=int, require=true, description="id")
     */
    public function toggle_collection() {
        $product_id = $this->request->post('product_id');
        $result = UserCollection::toggleCollection($this->auth->id, $product_id, UserCollection::TYPE_PRODUCT);
        $this->success('操作成功',['is_collection_count'=>$result?1:0]);
    }

    /**
     * 我的收藏列表
     */
    public function user_collection(){
        $params = $this->request->param('');
        $this->success('查询成功',UserCollection::productLists($params,$this->auth->id));

    }


    /**
     * 分享海报
     */
    public function poster_info() {

        $platform = $this->request->param('platform','wxmini');
        $id = $this->request->param('product_id');
        if(!$id){
            $this->error('参数错误');
        }
        $product = productModel::get($id);
        $root = '.';
        //$filename = md5(mt_rand()).'.png';
        $filename = $product->id.'.png';
        $oss = get_addon_info('alioss');
        if(!$oss || $oss['state'] != 1){
            $path = "/uploads/xilumarket/".date('Ymd').'/';
        }else{
            $path = "/uploads/xilumarket/".date('Ymd').'/';
        }
        if (!file_exists($root . $path)) {
            @mkdir($root . $path, 0777, true);
        }
        $qrcode = $path.$filename;
        $param = "id=".$product->id;
        if($this->auth->isLogin()){
            $param .= '&user_id='.$this->auth->id;
        }
        if($platform == 'h5'){
            $shopinfo = \app\common\model\xilumarket\Config::getMyConfig('shopinfo');
            $url = isset($shopinfo['h5_url'])?$shopinfo['h5_url']:request()->domain().'/h5/#/';
            QRcode::png($url.'pages/goods_detail/goods_detail?'.$param, $root.$qrcode, 'L', 6, 2);
            $product->qrcode = request()->domain().$qrcode;
        }else{
            $wxmini = new WeixinMini();
            $res = $wxmini->getUnlimited($param,'pages/goods_detail/goods_detail');
            if(!$res['status']){
                $this->error($res['msg']);
            }
            if(!get_addon_config('alioss')){
                file_put_contents($root.$qrcode,$res['file']);
            }else{
                Common::uploadAlioss($qrcode, $res['file']);
            }
            $product->qrcode = cdnurl($qrcode,true);
        }
        $user = $this->auth->getUser();
        $this->success('',[
            'text1'     =>  $product['name'],
            'text2'     =>  "二手闲置",
            'text3'     =>  '让您的闲置找到更多价值',
            'img1'      =>  $user->avatar,
            'img2'      =>  $product->qrcode,
            'img3'      =>  $product->thumb_image_text,
            'salesprice'=>  $product->salesprice,
            'line_price'=>  $product->line_price,
            'nickname'  =>  $user->nickname,
            'want_num'  =>  $product->want_num
        ]);
    }

}